package drds.plus.executor.function.scalar.datatime;

import drds.plus.executor.ExecuteContext;
import drds.plus.executor.function.scalar.ScalarFunction;
import drds.plus.executor.utils.Utils;
import drds.plus.sql_process.type.Type;

import java.util.Calendar;

/**
 * Returns the seconds argument, converted to hours, minutes, and seconds, setAliasAndSetNeedBuild
 * a TIME value. The range of the result is constrained to that of the TIME data
 * type. A warning occurs if the argument corresponds to a value outside that
 * range.
 *
 * <pre>
 * mysql> SELECT SEC_TO_TIME(2378);
 *         -> '00:39:38'
 * mysql> SELECT SEC_TO_TIME(2378) + 0;
 *         -> 3938
 * </pre>
 */
public class SecToTime extends ScalarFunction {

    public Object compute(ExecuteContext executeContext, Object[] args) {
        for (Object arg : args) {
            if (Utils.isNull(arg)) {
                return null;
            }
        }

        Integer sec = Type.IntegerType.convert(args[0]);
        Calendar cal = Calendar.getInstance();
        cal.set(0, 0, 0, 0, 0, 0);
        cal.set(Calendar.SECOND, sec);

        Type type = getReturnType();
        return type.convert(cal.getTime());
    }

    public Type getReturnType() {
        return Type.TimeType;
    }

    public String[] getFunctionNames() {
        return new String[]{"SEC_TO_TIME"};
    }
}
